package com.xinxing.city.recoverycheck.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Paint;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Handler;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Button;


import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.hikvision.netsdk.HCNetSDK;
import com.hikvision.netsdk.INT_PTR;
import com.hikvision.netsdk.NET_DVR_JPEGPARA;
import com.xinxing.city.recoverycheck.Control.SDKGuider;
import com.xinxing.city.recoverycheck.MainActivity;
import com.xinxing.city.recoverycheck.R;
import com.xinxing.city.recoverycheck.entitys.KernelAction;
import com.xinxing.city.recoverycheck.entitys.KernelActions;


import org.greenrobot.eventbus.EventBus;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class VideoSet {
//    private SurfaceView m_surfaceView = null;
    private SurfaceHolder m_surfaceView_holder = null;
    private SurfaceView m_surfaceView2 = null;
    private int m_iPreviewHandle = -1;
    private Button start;
    private Context context;
    private MainActivity mainActivity;
    private SharedPreferences sharedPreferences;
    private Camera camera;
    private Camera.Parameters parameters;
    private SurfaceHolder mSurfaceHolder;

    private Integer position = 0;
    private SurfaceHolder holder;
    private Gson gson;
    private String codeYz = "";
    private String videoUrl;
    public String token;

    //普通摄像头
    private List<String> imageUrl = new ArrayList<>();
    private Integer imageF = 1;
    private Integer imageJc = 1; //1 开始 2 开始摄像头 3 保存图片
    private Boolean isLoad = false;
    private Boolean isLoads = false;
    private Handler handler = null;
    private Boolean isRecode = true;
    private Runnable runnable;
    private Integer imageNum;

    //海康摄像头
    private Handler handler1 = null;
    private Boolean isRecode1 = true;
    private Runnable runnable1;
    private Integer imageNum1;
    private List<String> imageUrl1 = new ArrayList<>();;
    private Integer imageF1 = 1;
    private Integer imageJc1 = 1; //1 开始 2 开始摄像头 3 保存图片
    private int lUserID=-1;
    public VideoSet(Context cont) {
        context = cont;
        mainActivity = (MainActivity) cont;
        gson = new Gson();

        sharedPreferences = context.getSharedPreferences("MyPrefs",Context.MODE_PRIVATE);
        position = sharedPreferences.getInt("camera_id",0);

//        m_surfaceView = mainActivity.findViewById(R.id.SuView);
//        mSurfaceHolder = m_surfaceView.getHolder();
        m_surfaceView2 = mainActivity.findViewById(R.id.HkView);
//        initSurface();
        Hk();
    }

    //海康
    private void Hk() {
        start = mainActivity.findViewById(R.id.button_preview_start);
        holder = m_surfaceView2.getHolder();
        //m_surfaceView2.setZOrderOnTop(true);

        try{
            Hk hk = new Hk(context,"192.168.1.64","admin","Xx135246","8000");
            lUserID= hk.initVideo();
        } catch (Exception e) {

        }

    }

    public void initSurface() {
        mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder surfaceHolder) {
                Log.e("12345612","aa");
            }
            @Override
            public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
                Log.e("12345634","bb");
            }
            @Override
            public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
                Log.e("12345656","ff");
            }
        });
    }

    //监控
    public void videoStart(Integer i) {
        try {
            if (camera != null) stopCamera(0);
            camera = Camera.open(i);
            startCamera(0, mSurfaceHolder);
            imageJc = 2;
            isLoad = false;
        } catch (Exception e) {
            camera = null;
            initCar();
            e.printStackTrace();
        }
    }

    private void startCamera(int cameraId, SurfaceHolder holder) {

        if (camera != null) {
            try {
                parameters = camera.getParameters();
                parameters.setPictureFormat(ImageFormat.JPEG);
                parameters.setPreviewSize(1920, 1080);
                parameters.setPictureSize(1920, 1080);
                parameters.setPreviewFrameRate(30);
                camera.setParameters(parameters);
                camera.setPreviewDisplay(holder);
                camera.startPreview();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void stopCamera(int cameraId) {
        if (camera != null) {
            camera.stopPreview();
            camera.release();
            camera = null;
        }
    }





    // 执行截图操作
    public void takePicture1(int num, String code) {

        codeYz = code;
        imageNum1 = num;

        if (num == 1) {
            imageF1 = 1;
            imageUrl1 = new ArrayList<>();
        }
        Log.e("kong","海康拍照"+1);
        //删除旧文件
        String filePath=context.getExternalFilesDir(null).getAbsolutePath()+"/imaget"+imageNum1+".jpg";
        File file=new File(filePath);
        if(file.exists()){
            file.delete();
        }
        SDKGuider.g_sdkGuider.m_comPreviewGuider.RealPlay_Stop_jni(m_iPreviewHandle);
//        m_surfaceView.setVisibility(View.INVISIBLE);
        refreshThread(filePath);
    }
    private void refreshThread(String path) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                NET_DVR_JPEGPARA PARA = new NET_DVR_JPEGPARA();
                PARA.wPicQuality = 0;
                PARA.wPicSize = 13;
                int iBufferSize = 2448 * 2048;
                byte[] sbuffer = new byte[iBufferSize];
                INT_PTR bytesRerned = new INT_PTR();
                Log.e("kong","海康拍照"+2);
                boolean flag = HCNetSDK.getInstance().NET_DVR_CaptureJPEGPicture_NEW(lUserID, 1, PARA, sbuffer, iBufferSize, bytesRerned);
                if (flag) {
                    Log.e("kong","海康拍照"+3);
                    Bitmap bitmap = BitmapFactory.decodeByteArray(sbuffer, 0, sbuffer.length);
                    try {
                        saveFile(bitmap,path);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                } else {
                    Log.e("photo","error");
//                    XLog.e("NET_DVR_ERROR:" + HCNetSDK.getInstance().NET_DVR_GetLastError());
                }
            }
        }).start();
    }

    /**
     * 保存文件
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public boolean saveFile(Bitmap bm, String fileName) throws IOException {
        File myCaptureFile = new File( fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
        File file = new File(fileName);
        Log.e("kong","海康拍照"+4);
        if (file.exists()) {
            List<String> params5 = new ArrayList<>();
            params5.add(file.getPath());
            EventBus.getDefault().post(new KernelAction(KernelActions.HK, params5));
//            saveBitmapToFile1(file);
        } else {
//            XLog.e("海康文件不存在");
        }
        return true;
    }
    public void test(File file) throws IOException {
        Bitmap b = BitmapFactory.decodeFile(file.getPath());
        Bitmap newB =  addTextWatermark(b,20, Color.RED,0,0,true);


        File myCaptureFile = new File( file.getPath());
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        newB.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();

    }


    //录像操作
    public void hkStartRecode() {
        videoUrl = "";
        Boolean as = SDKGuider.g_sdkGuider.m_comPreviewGuider.RealPlay_Record(m_iPreviewHandle, 1,"/sdcard/recordings.mp4");
        if (as) {
            Log.e("录像开启","录像开启"+HCNetSDK.getInstance().NET_DVR_GetLastError());
            isRecode = true;
        }  else {
            isRecode = false;
            Log.e("录像开启失败","录像失败");
        }
    }



    public interface HkStopRecodeBack {
        void onSuccess(String url);
    }

    //初始化下一次操作
    public void initCar() {
        imageF ++;
        imageJc = 1;
        isLoad = false;
        isLoads = false;
    }

    public void initCar1() {
        imageF1 ++;
        imageJc1 = 1;
    }

    //关闭摄像头信息
    public void close() {
        imageF  = 1;
        imageJc = 1;

        imageF1  = 1;
        imageJc1 = 1;

        if (handler != null && runnable != null) handler.removeCallbacks(runnable);
        if (handler1 != null && runnable1 != null) handler1.removeCallbacks(runnable1);
        if (camera != null) stopCamera(0);

        handler = null;
        runnable = null;
        handler1 = null;
        runnable1 = null;

        isLoad = false;
    }

    //隐藏
    private void vHide(){
        //m_surfaceView.setVisibility(View.INVISIBLE);
        //m_surfaceView2.setVisibility(View.INVISIBLE);
    }
    /**
     * 给图片添加水印 当需要换行的时候，推荐使用StaticLayout 这种实现方式
     * @param src 原bitmap
     * @param textSize 文字大小
     * @param x  距离图片位图的左边距
     * @param y   距离图片位图的上边距
     * @param recycle  是否回收bitmap，建议true
     * */
    public Bitmap addTextWatermark(Bitmap src, int textSize, int color, float x, float y, boolean recycle) {
        Objects.requireNonNull(src, "src is null");
        Bitmap ret = src.copy(src.getConfig(), true);
        TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
        Canvas canvas = new Canvas(ret);
        paint.setColor(color);
        paint.setTextSize(80);
        Rect bounds = new Rect();
        String content = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        /*
        单行文字的实现代码
        paint.getTextBounds(content, 0, content.length(), bounds);
        canvas.drawText(content, x, y, paint);*/

        canvas.translate(x, y);
        StaticLayout myStaticLayout = new StaticLayout(content, paint, canvas.getWidth(), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
        myStaticLayout.draw(canvas);

//        canvas.drawBitmap(bitmap, 0, 0, null);//绘制小图片使用的代码
        if (recycle && !src.isRecycled()) src.recycle();
        return ret;
    }

}
